/*
 * Copyright (c) 2010 Mathew Hall, University of Sheffield.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided
 * with the distribution.
 *
 * Neither the name of the University of Sheffield nor the names of its
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package search.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import primitives.cluster.ClusterHead;
import primitives.graph.Graph;
import primitives.graph.Node;

//foo bar baz

public abstract class TreeLoader {

	static Pattern definitionLine = Pattern.compile("\\W*(.+?)\\W*\\[.*\\]");
	
	static Pattern transitionLine = Pattern.compile("\\W*\"?" + "([^\"]+)"
			+ "\"?" + "\\W*" + "->" + "\\W*" + "\"?" + "([^\"]+)" + "\"?"
			+ "\\W*" + "(\\[" + "(.*)" + "\\])?");

        public static ClusterHead loadTreeFromDot(File input) throws IOException{
            Graph g = new Graph();
            BufferedReader in = new BufferedReader(new FileReader(input));
            String line;
		HashMap<String, Node> nodes = new HashMap<String, Node>();

		while ((line = in.readLine()) != null) {
			if (line.matches("^\\W*#.*$"))
                            continue;
			Matcher m = definitionLine.matcher(line);
			if (m.matches()) {
				Matcher m2 = transitionLine.matcher(line);
				if (m2.matches()) {
					String s1 = m2.group(1);
					String s2 = m2.group(2);
					// String s3 = m2.group(3);
					nodes.put(s1, new Node(s1));
					nodes.put(s2, new Node(s2));
				} else {
					String s1 = m.group(1);
					nodes.put(s1, new Node(s1));
				}
			}
		}

		for (String k : nodes.keySet()) {
			g.addNode(nodes.get(k));
		}

		in = new BufferedReader(new FileReader(input));

		while ((line = in.readLine()) != null) {
			Matcher m = transitionLine.matcher(line);
			if (line.matches("^\\W*#.*$"))
				continue;
			if (m.matches()) {
                                Logger.getLogger(TreeLoader.class.getName()).log(Level.FINEST, String.format("Line \"%s\" matches definition",line));
				Matcher m2 = transitionLine.matcher(line);
				if (m2.matches()) {
					String s1 = m2.group(1);
					String s2 = m2.group(2);
					String s3 = m2.group(4);
					
						if (s3 == null)
							s3 = "";
                                                s3 = s3.replace("[", "");
                                                s3 = s3.replace("];", "");
                                                s3 = s3.replace("]","");
                                                s3 = s3.replace("[]","");
                                        try{
                                            nodes.get(s1).getLabel();
                                            nodes.get(s2).getLabel();
						nodes.get(s1).connect(nodes.get(s2), s3);
					}catch(NullPointerException npe){
                                            Logger.getLogger(TreeLoader.class.getName()).log(Level.WARNING, String.format("Tried to connect %s to %s via %s",s1,s2,s3), npe);
                                        }
				}
			}
		}

		return new ClusterHead(g);
        }
	public static ClusterHead loadTreeFromDotS(String input) {
		Graph g = new Graph();
		String[] lines = input.split("\r\n|\r|\n");
		HashMap<String, Node> nodes = new HashMap<String, Node>();

		for (String line : lines) {
			if (line.matches("^\\W*#.*$"))
				continue;
			Matcher m = definitionLine.matcher(line);
			if (m.matches()) {
				Matcher m2 = transitionLine.matcher(line);
				if (m2.matches()) {
					String s1 = m2.group(1);
					String s2 = m2.group(2);
					// String s3 = m2.group(3);
					nodes.put(s1, new Node(s1));
					nodes.put(s2, new Node(s2));
				} else {
					String s1 = m.group(1);
					nodes.put(s1, new Node(s1));
				}
			} else {

			}
		}

		for (String k : nodes.keySet()) {
			g.addNode(nodes.get(k));
		}

		for (String line : lines) {
			Matcher m2 = transitionLine.matcher(line);
			if (m2.matches()) {
				String s1 = m2.group(1);
				String s2 = m2.group(2);
				String s3 = m2.group(3);
				nodes.get(s1).connect(nodes.get(s2), s3);
			}
		}

		return new ClusterHead(g);

	}

	public static ClusterHead loadTreeFromDot(String filename)
			throws IOException {
		
                        return loadTreeFromDot(new File(filename));
		
		

	}
}
